package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3.如果是登录请求则直接放行
        if (request.getURI().getPath().contains("/admin/login")) {
            return chain.filter(exchange);
        }

        //4.获取请求头
        HttpHeaders headers = request.getHeaders();

        //5.在请求头中获取token
        String token = headers.getFirst("token");

        //6.判断token是否为空,如果为空,则直接响应错误信息
        if (StringUtils.isEmpty(token)) {
            //在响应中放入返回码,没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }

        //6.1 判断token是否合法,如果不合法则直接响应错误信息
        try {
            //对token进行解析
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //解析错误.说明令牌过期或者伪造不合法等问题
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.2 如果合法则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
